package com.yoomiito.app.ui.search.youpin

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import cn.droidlover.xdroidmvp.cache.SharedPref
import com.chad.library.adapter.base.BaseQuickAdapter
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.yoomiito.app.R
import com.yoomiito.app.adapter.goods.list.sort.ThemeYouPinGoodsAdapter
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.gift.GiftData
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.SpacingDecoration
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType
import com.yoomiito.app.widget.state.StatusManager
import kotlinx.android.synthetic.main.act_search_result.*
import kotlinx.android.synthetic.main.item_search.*
import kotlinx.android.synthetic.main.item_search_toolbar.*

class YouPinSearchResultActivity :BaseActivity<YouPinSearchResultPresenter>(){

    companion object{
        fun start(context: Context,keyWord:String,defaultKeyWord:String){
            val intent = Intent(context,YouPinSearchResultActivity::class.java)
            intent.putExtra(Const.Common.Data,keyWord)
            intent.putExtra(Const.Common.Key,defaultKeyWord)
            context.startActivity(intent)
        }
    }

    var mRecyclerView: androidx.recyclerview.widget.RecyclerView? = null
    var mSwipeRefreshLayout: SmartRefreshLayout? = null
    private var goodsAdapter = ThemeYouPinGoodsAdapter(null)
    private var key: String = ""
    private var sort = ""
    private var hasCoupon = 0
    private var currentPage = 1
    private var mDefaultKeyWord = ""//后台配置默认搜索关键字
    override fun getLayoutId(): Int = R.layout.act_search_result

    override fun newP(): YouPinSearchResultPresenter = YouPinSearchResultPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        mStatusManager = StatusManager.Builder(this)
                .addType(ContentType(R.layout.item_refresh_rcy))
                .addType(EmptyType().setEmptyContent("未找到相关商品"))
                .build()
        item_search_et.hint = "输入优品商品名"
        mRecyclerView = mStatusManager.view().findViewById(R.id.act_search_result_rcy)
        mSwipeRefreshLayout = mStatusManager.view().findViewById(R.id.act_result_refreshLayout)
        frameLayout.addView(mStatusManager.view())
        key = intent.getStringExtra(Const.Common.Data)
        mDefaultKeyWord = intent.getStringExtra(Const.Common.Key)
        item_search_et.setText(key)
        window.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        item_search_del.visibility = View.VISIBLE
        item_search_et.setTextColor(ResUtil.getColor(R.color.color_ff5100))
        initClicks()
        initTabLayout()
        initRcy()
        initRefreshLayout()
    }

    private fun initClicks() {
        act_search_back.setOnClickListener { finish() }
        act_search_search.setOnClickListener {
            key = item_search_et.text.toString().trim { it <= ' ' }
            if (TextUtils.isEmpty(key)) {
                if(mDefaultKeyWord.isEmpty()){
                    showToast("请输入搜索内容")
                    return@setOnClickListener
                }
                key = mDefaultKeyWord
            }
            val serachList = SharedPref.getInstance(App.getInstance()).getListData(Const.Common.YouSearchHistory, String::class.java)
            if (serachList.size >= 8) {
                serachList.removeAt(0)
            }
            if (!serachList.contains(key)) {
                serachList.add(0, key)
                SharedPref.getInstance(App.getInstance()).putListData(Const.Common.YouSearchHistory, serachList)
            }
            currentPage = 1
            mSwipeRefreshLayout!!.autoRefresh()
        }
        item_search_del.setOnClickListener {
            item_search_et.setText("")
            item_search_et.hint = if (mDefaultKeyWord.isEmpty()) "输入优品商品名" else mDefaultKeyWord
        }
    }

    private fun initRefreshLayout() {
        mSwipeRefreshLayout!!.setOnRefreshListener { refreshLayout: RefreshLayout? ->
            currentPage = 1
            p!!.searchGoods(key, sort, currentPage)
        }
        mSwipeRefreshLayout!!.setOnLoadMoreListener { refreshLayout: RefreshLayout? ->
            currentPage++
            p!!.searchGoods(key, sort, currentPage)
        }
        mSwipeRefreshLayout!!.autoRefresh()
    }

    private fun initRcy() {
        val layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this, androidx.recyclerview.widget.LinearLayoutManager.VERTICAL, false)
        mRecyclerView?.layoutManager = layoutManager
        mRecyclerView?.itemAnimator = androidx.recyclerview.widget.DefaultItemAnimator()
        mRecyclerView?.addItemDecoration(SpacingDecoration(DensityUtil.dp2px(12f),DensityUtil.dp2px(12f),false))
        mRecyclerView?.adapter = goodsAdapter
        goodsAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            RouterUtils.toGoodsDetail(this@YouPinSearchResultActivity, goodsAdapter.data[position].id.toString(),Type.GoodsType.YouPin)
        }
    }

    private fun initTabLayout() {
        act_result_tabView.setPriceFirstName("sale_price")
        act_result_tabView.setSaleFirstName("volume")
        act_result_tabView.setDefault()
        act_result_tabView.dismissCoupon()
        act_result_tabView.divVisible(true)
//        act_result_tabView.setOnChangeListener { sort: String, hasCoupon: Int ->
//            this@YouPinSearchResultActivity.sort = sort
//            this@YouPinSearchResultActivity.hasCoupon = hasCoupon
//            currentPage = 1
//            showLoading()
//            mSwipeRefreshLayout?.setNoMoreData(false)
//            p!!.searchGoods(key, sort, currentPage)
//        }
    }

    fun setData(goodsInfos: GiftData?) {
        dismissLoading()
        if(goodsInfos == null){
            return
        }
        if (goodsInfos?.current_page == 1) {
            if (goodsInfos?.data.isEmpty()) {
                mStatusManager.showEmpty()
            } else {
                goodsAdapter.setNewData(goodsInfos?.data)
                mStatusManager.showContent()
            }
            mSwipeRefreshLayout?.finishRefresh(true)
        } else {
            goodsAdapter.addData(goodsInfos?.data!!)
            mSwipeRefreshLayout?.finishLoadMore(true)
        }
        if (goodsInfos?.current_page==goodsInfos?.last_page) {
            mSwipeRefreshLayout?.finishLoadMoreWithNoMoreData()
        }
        currentPage = goodsInfos?.current_page!!
    }

}